﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Domain.Abstract;
using Domain.Concrete;
using Domain.Entity;
using Pro260Website.Areas.Admin.Models;
using Pro260Website.Models;

namespace Pro260Website.Areas.Admin.Controllers
{
    [Authorize(Roles="Admin")]
    public class AccountController : Controller
    {
        private readonly IAccountRepository _accountRepository;

        public AccountController(IAccountRepository accountRepository)
        {

            this._accountRepository = accountRepository;
        }

        public ActionResult Index(int page = 1, int pageSize = 20)
        {
            var items = _accountRepository.Accounts;

            return View(new ListingViewModel<Account>
            {
                Items = items.OrderBy(g => g.Id).Skip((page - 1) * pageSize).Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = pageSize,
                    TotalItems = items.Count()
                }
            });
        }

        [HttpPost]
        public ActionResult SaveChangesToUser(UserSecurityViewModel model)
        {
            MembershipUser user = Membership.GetUser(model.Username);
            user.IsApproved = !model.IsBanned;
            Membership.UpdateUser(user);

            Roles.RemoveUserFromRoles( user.UserName, Roles.GetRolesForUser(user.UserName));
            Roles.AddUserToRole(user.UserName, model.Role);

            return RedirectToAction("Index");

        }

        [HttpPost]
        public ActionResult DeleteUser(UserSecurityViewModel model)
        {
            MembershipUser user = Membership.GetUser(model.Username);

            _accountRepository.DeleteAccount(_accountRepository.Accounts.SingleOrDefault(a => a.Username == user.UserName));
            Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName));
            Membership.DeleteUser(user.UserName);
            return RedirectToAction("Index");
        }
    }
}
